package me.zhengjie.modules.enrstu.rest;


import cn.hutool.core.util.IdcardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousGetMapping;
import me.zhengjie.modules.enrstu.service.FileInformationService;
import me.zhengjie.modules.enrstu.service.SignUpService;
import me.zhengjie.modules.enrstu.service.dto.SignUpFileInfoCURDHeaderDto;
import me.zhengjie.modules.enrstu.service.dto.SignUpReportInfoRequest;
import me.zhengjie.utils.resp.Result;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.InputStream;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "报名管理:家长填报")
@RequestMapping("/api/enrstu/signUp")
public class SignUpController {
    private final FileInformationService fileInformationService;
    private final SignUpService signUpService;

    @PostMapping("/saveOrSubmit")
    @Log("保存/提交填报信息")
    @ApiOperation("保存填报信息")
    @PreAuthorize("@el.check('signUp:add') And @el.check('signUp:edit')")
    public ResponseEntity<Object> saveOrSubmit(@RequestPart(value = "request") SignUpReportInfoRequest request, @RequestPart("file") List<MultipartFile> file ){
        log.info("保存/提交填报信息:{}",request);
        return new ResponseEntity<>(signUpService.saveOrSubmit(request, file)? Result.ok() : Result.error(),HttpStatus.CREATED);
    }




    @GetMapping("/info/prompt")
    @Log("获取提醒区信息")
    @ApiOperation("获取提醒区信息")
    @PreAuthorize("@el.check('signUp:query')")
    public ResponseEntity<Object> getPrompt(){
        log.info("获取提醒区信息:{}",signUpService.getPrompt());
        return new ResponseEntity<>(Result.ok().message(signUpService.getPrompt()),HttpStatus.OK);
    }

    @GetMapping("/info/list/{logId}")
    @Log("获取报名情况区列表和详情")
    @ApiOperation("获取报名情况区列表和详情")
    @PreAuthorize("@el.check('signUp:list')")
    public ResponseEntity<Object> getList(@PathVariable String logId){
        return new ResponseEntity<>(Result.ok().data("Data",signUpService.getListAndDetail(logId)),HttpStatus.OK);
    }

    @GetMapping("/info/birthday")
    @Log("获取出生年月")
    @ApiOperation("获取出生年月")
    @PreAuthorize("@el.check('signUp:query')")
    public ResponseEntity<Object> getBirthday(@RequestParam String idCard){
        return new ResponseEntity<>(IdcardUtil.getBirthByIdCard(idCard),HttpStatus.OK);
    }

    @GetMapping("/info/guardian")
    @Log("获取监护人信息")
    @ApiOperation("获取监护人信息")
    @PreAuthorize("@el.check('signUp:query')")
    public ResponseEntity<Object> getGuardianInfo(@RequestParam String idCard){
        return new ResponseEntity<>(signUpService.getGuardianInfo(idCard),HttpStatus.OK);
    }

    @AnonymousGetMapping("/info/administrativeDivision")
    @Log("获取行政区信息")
    @ApiOperation("获取行政区信息")
    public ResponseEntity<Object> getAdministrativeDivision(@RequestParam(required = false) Long id){
        return new ResponseEntity<>(signUpService.findAdministrativeDivision(id),HttpStatus.OK);
    }
    @GetMapping("/info/enrollmentParameter")
    @Log("获取报名参数表信息")
    @ApiOperation("获取报名参数表信息")
    @PreAuthorize("@el.check('signUp:query')")
    public ResponseEntity<Object> getEnrollmentParameter(@ApiParam(value = "NATION='民族'; ATTACHMENT='附件'，'Beneficiaries=政策性照顾对象'")
                                                             @RequestParam  String label){
        return new ResponseEntity<>(signUpService.findByTypeLabel(label),HttpStatus.OK);
    }
    @GetMapping("/info/school")
    @Log("就近入学获取学校信息")
    @ApiOperation("就近入学获取学校信息")
    @PreAuthorize("@el.check('signUp:query')")
    public ResponseEntity<Object> getSchoolInfo(Long communityAdId, Boolean isPolicyCare){
        return new ResponseEntity<>(signUpService.findSchoolList(communityAdId,isPolicyCare),HttpStatus.OK);
    }



    @GetMapping("/file/download/{linkId}/{fileAttachmentCode}")
    @Log("下载附件信息")
    @ApiOperation("下载附件信息")
    @PreAuthorize("@el.check('signUp:dowload')")

    public ResponseEntity<StreamingResponseBody> downloadFile(@PathVariable String linkId, @PathVariable String fileAttachmentCode) {
        byte[] zipBytes = fileInformationService.fileDownload(linkId, fileAttachmentCode);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(out -> {
                    try (InputStream is = new java.io.ByteArrayInputStream(zipBytes)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to write file to response", e);
                    }
                });
    }

    @DeleteMapping("/file/delete")
    @Log("删除附件信息")
    @ApiOperation("删除附件信息")
    @PreAuthorize("@el.check('signUp:delect')")
    public ResponseEntity<Object> deleteFile(@ApiParam(value = "附件删除：id=true;批量删除-类型：linkId=true,fileAttachmentCode=true;批量删除-全量：linkId=true;") @RequestBody SignUpFileInfoCURDHeaderDto signUpFileInfoCURDHeaderDto){
        return new ResponseEntity<>( fileInformationService.fileDelete(signUpFileInfoCURDHeaderDto) ? Result.ok() : Result.error(),HttpStatus.OK);
    }
}
